package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.constant.ClueStatusConstants;
import com.qk.common.constant.ClueTrackRecordType;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.domain.clue.ClueDO;
import com.qk.dto.club.*;
import com.qk.entity.Business;
import com.qk.entity.Clue;
import com.qk.entity.ClueTrackRecord;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.mapper.ClueTrackRecordMapper;
import com.qk.management.service.ClueService;
import com.qk.management.service.UserService;
import com.qk.vo.clue.CluePoolVO;
import com.qk.vo.clue.ClueVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Objects;

@Service
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {

    @Autowired
    private ClueTrackRecordMapper clueTrackRecordMapper;
    @Autowired
    private UserService userService;

    @Autowired
    private BusinessMapper businessMapper;


    @Override
    public PageResult<CluePoolVO> getCluePoolList(CluePoolPageDTO dto) {
        Page<CluePoolVO> list = this.baseMapper.selectCluePoolPageList(new Page<>(dto.getPage(), dto.getPageSize()), dto);
        System.out.println(list);
        return PageResult.<CluePoolVO>builder()
                .total(list.getTotal())
                .rows(list.getRecords())
                .build();
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateFakeClue(ClueFakeDTO dto) {
        if (BeanUtil.hasNullField(dto, "remark")) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        this.baseMapper.updateById(Clue.builder()
                .status(ClueStatusConstants.FAKE_CLUE)
                .id(dto.getId())
                .updateTime(LocalDateTime.now())
                .build());
        this.clueTrackRecordMapper.insert(ClueTrackRecord.builder()
                .clueId(dto.getId())
                .userId(CurrentUserContextHolders.get())
                .record(dto.getRemark())
                .type(ClueTrackRecordType.FAKE)
                .falseReason(dto.getReason())
                .createTime(LocalDateTime.now())
                .build()
        );
    }


    @Transactional
    @Override
    public void toBusiness(Integer id) {
        Clue clue = this.baseMapper.selectById(id);

        clue.setStatus(ClueStatusConstants.CONVERT_TO_BUSINESS);

        clue.setUpdateTime(LocalDateTime.now());

        this.baseMapper.updateById(clue);

        Business business = BeanUtil.copyProperties(clue, Business.class);

        business.setId(null);

        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());

        business.setNextTime(null);

        business.setUserId(null);

        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);

        business.setClueId(id);

        this.businessMapper.insert(business);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateClueInfoById(UpdateClueInfoDTO dto) {
        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        clue.setUpdateTime(LocalDateTime.now());

        if (dto.getStatus().equals(ClueStatusConstants.WAIT_FOLLOW_UP))
            clue.setStatus(ClueStatusConstants.FOLLOW_UP);
        this.baseMapper.updateById(clue);

        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(dto, ClueTrackRecord.class);
        // 2.2 将id置为 null
        clueTrackRecord.setId(null);
        // 2.3 设置当前线索跟进记录的 线索id
        clueTrackRecord.setClueId(clue.getId());
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        clueTrackRecord.setType(ClueTrackRecordType.NORMAL);
        // TODO 设置跟进用户id当前用户，此时当前用户的id还在拦截器中
        clueTrackRecord.setUserId(CurrentUserContextHolders.get());
        this.clueTrackRecordMapper.insert(clueTrackRecord);
    }


    @Override
    public ClueVO getClueById(Integer id) {
        Clue clue = this.baseMapper.selectById(id);
        ClueVO clueVO = BeanUtil.copyProperties(clue, ClueVO.class);
        // 设置跟进记录
        clueVO.setTrackRecords(clueTrackRecordMapper
                .selectList(Wrappers.lambdaQuery(ClueTrackRecord.class)
                        .in(ClueTrackRecord::getClueId, id)
                ).stream().map(item -> {
                    ClueVO.ClueTrackRecordVO vo = BeanUtil.copyProperties(item, ClueVO.ClueTrackRecordVO.class);
                    vo.setAssignName(userService.getUserById(clue.getUserId()).getName());
                    return vo;
                }).toList());
        return clueVO;
    }

    @Override
    public PageResult<ClueDO> getCluePageList(CluePageDTO dto) {
        Page<ClueDO> list = this.baseMapper.selectPageList(new Page<>(dto.getPage(), dto.getPageSize()), dto);
        return PageResult.<ClueDO>builder()
                .total(list.getTotal())
                .rows(list.getRecords())
                .build();
    }


    @Override
    public void addClub(ClueDTO dto) {
        if (Objects.isNull(dto.getPhone()) || Objects.isNull(dto.getChannel())) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        clue.setStatus(ClueStatusConstants.WAIT_ALLOCATION);
        clue.setCreateTime(LocalDateTime.now());
        clue.setUpdateTime(LocalDateTime.now());
        this.save(clue);

    }

}
